<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blogwebpage/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blogwebpage/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/blogwebpage/images/favicon.ico">
  <link rel="mask-icon" href="/blogwebpage/images/logo.svg" color="#222">
  <meta name="msvalidate.01" content="9BDlx6FiNE">

<link rel="stylesheet" href="/blogwebpage/css/main.css">


<link rel="stylesheet" href="/blogwebpage/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wangkejie.gitee.io","root":"/blogwebpage/","scheme":"Gemini","version":"7.8.0","exturl":true,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="main()调用之前的加载过程App开始启动后，系统首先加载可执行文件（自身App的所有.o文件的集合），然后加载动态链接库dyld，dyld是一个专门用来加载动态链接库的库。 执行从dyld开始，dyld从可执行文件的依赖开始, 递归加载所有的依赖动态链接库。动态链接库包括：iOS 中用到的所有系统 framework，加载OC runtime方法的libobjc，系统级别的libSystem，">
<meta property="og:type" content="article">
<meta property="og:title" content="app启动优化">
<meta property="og:url" content="https://wangkejie.gitee.io/blogwebpage/iOS/interview/applaunchspeed.html">
<meta property="og:site_name" content="王科杰">
<meta property="og:description" content="main()调用之前的加载过程App开始启动后，系统首先加载可执行文件（自身App的所有.o文件的集合），然后加载动态链接库dyld，dyld是一个专门用来加载动态链接库的库。 执行从dyld开始，dyld从可执行文件的依赖开始, 递归加载所有的依赖动态链接库。动态链接库包括：iOS 中用到的所有系统 framework，加载OC runtime方法的libobjc，系统级别的libSystem，">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://wangkejie.gitee.io/blogwebpage/images/iOS/applaunch_macho.jpeg">
<meta property="og:image" content="https://wangkejie.gitee.io/blogwebpage/images/iOS/applaunch_dyld.jpeg">
<meta property="article:published_time" content="2017-07-15T03:26:39.000Z">
<meta property="article:modified_time" content="2021-06-25T08:55:53.143Z">
<meta property="article:author" content="Jack Wang">
<meta property="article:tag" content="app启动优化">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://wangkejie.gitee.io/blogwebpage/images/iOS/applaunch_macho.jpeg">

<link rel="canonical" href="https://wangkejie.gitee.io/blogwebpage/iOS/interview/applaunchspeed.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>app启动优化 | 王科杰</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?93e26277de0cf2c5851167f2c6dcaa7d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blogwebpage/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">王科杰</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Jack's Notes</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blogwebpage/" rel="section"><i class="home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blogwebpage/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">52</span></a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blogwebpage/me/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blogwebpage/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">54</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blogwebpage/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">56</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/interview/applaunchspeed.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          app启动优化
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-07-15 11:26:39" itemprop="dateCreated datePublished" datetime="2017-07-15T11:26:39+08:00">2017-07-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/" itemprop="url" rel="index"><span itemprop="name">面试总结</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/app%E5%90%AF%E5%8A%A8%E4%BC%98%E5%8C%96/" itemprop="url" rel="index"><span itemprop="name">app启动优化</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="main-调用之前的加载过程"><a href="#main-调用之前的加载过程" class="headerlink" title="main()调用之前的加载过程"></a>main()调用之前的加载过程</h1><p>App开始启动后，系统首先加载可执行文件（自身App的所有.o文件的集合），然后加载动态链接库dyld，dyld是一个专门用来加载动态链接库的库。 执行从dyld开始，dyld从可执行文件的依赖开始, 递归加载所有的依赖动态链接库。<br>动态链接库包括：iOS 中用到的所有系统 framework，加载OC runtime方法的libobjc，系统级别的libSystem，例如libdispatch(GCD)和libsystem_blocks (Block)。<br>其实无论对于系统的动态链接库还是对于App本身的可执行文件而言，他们都算是image（镜像），而每个App都是以image(镜像)为单位进行加载的，那么image究竟包括哪些呢？</p>
<h2 id="系统使用动态链接有几点好处："><a href="#系统使用动态链接有几点好处：" class="headerlink" title="系统使用动态链接有几点好处："></a>系统使用动态链接有几点好处：</h2><p>代码共用：很多程序都动态链接了这些 lib，但它们在内存和磁盘中中只有一份。 易于维护：由于被依赖的 lib 是程序执行时才链接的，所以这些 lib 很容易做更新，比如libSystem.dylib 是 libSystem.B.dylib 的替身，哪天想升级直接换成libSystem.C.dylib 然后再替换替身就行了。 减少可执行文件体积：相比静态链接，动态链接在编译时不需要打进去，所以可执行文件的体积要小很多。</p>
<img src="/blogwebpage/images/iOS/applaunch_macho.jpeg" class="" title="applaunch_macho">

<p>如上图所示，不同进程之间共用系统dylib的_TEXT区，但是各自维护对应的_DATA区。<br>所有动态链接库和我们App中的静态库.a和所有类文件编译后的.o文件最终都是由dyld(the dynamic link editor)，Apple的动态链接器来加载到内存中。每个image都是由一个叫做ImageLoader的类来负责加载（一一对应），那么ImageLoader又是什么呢？</p>
<h2 id="什么是ImageLoader"><a href="#什么是ImageLoader" class="headerlink" title="什么是ImageLoader"></a>什么是ImageLoader</h2><p>image 表示一个二进制文件(可执行文件或 so 文件)，里面是被编译过的符号、代码等，所以 ImageLoader 作用是将这些文件加载进内存，且每一个文件对应一个ImageLoader实例来负责加载。<br>两步走： 在程序运行时它先将动态链接的 image 递归加载 (也就是上面测试栈中一串的递归调用的时刻)。 再从可执行文件 image 递归加载所有符号。<br>当然所有这些都发生在我们真正的main函数执行前。</p>
<h2 id="动态链接库加载的具体流程"><a href="#动态链接库加载的具体流程" class="headerlink" title="动态链接库加载的具体流程"></a>动态链接库加载的具体流程</h2><p>动态链接库的加载步骤具体分为5步：</p>
<ul>
<li><p>load dylibs image 读取库镜像文件</p>
</li>
<li><p>Rebase image</p>
</li>
<li><p>Bind image</p>
</li>
<li><p>Objc setup</p>
</li>
<li><p>initializers</p>
</li>
</ul>
<h3 id="load-dylibs-image"><a href="#load-dylibs-image" class="headerlink" title="load dylibs image"></a>load dylibs image</h3><p>在每个动态库的加载过程中， dyld需要：</p>
<ul>
<li>分析所依赖的动态库</li>
<li>找到动态库的mach-o文件</li>
<li>打开文件</li>
<li>验证文件</li>
<li>在系统核心注册文件签名</li>
<li>对动态库的每一个segment调用mmap()</li>
</ul>
<p>通常的，一个App需要加载100到400个dylibs， 但是其中的系统库被优化，可以很快的加载。 针对这一步骤的优化有：</p>
<ul>
<li>减少非系统库的依赖</li>
<li>合并非系统库</li>
<li>使用静态资源，比如把代码加入主程序</li>
</ul>
<h3 id="rebase-bind"><a href="#rebase-bind" class="headerlink" title="rebase/bind"></a>rebase/bind</h3><p>由于ASLR(address space layout randomization)的存在，可执行文件和动态链接库在虚拟内存中的加载地址每次启动都不固定，所以需要这2步来修复镜像中的资源指针，来指向正确的地址。 rebase修复的是指向当前镜像内部的资源指针； 而bind指向的是镜像外部的资源指针。<br>rebase步骤先进行，需要把镜像读入内存，并以page为单位进行加密验证，保证不会被篡改，所以这一步的瓶颈在IO。bind在其后进行，由于要查询符号表，来指向跨镜像的资源，加上在rebase阶段，镜像已被读入和加密验证，所以这一步的瓶颈在于CPU计算。<br>通过命令行可以查看相关的资源指针:</p>
<blockquote>
<p>xcrun dyldinfo -rebase -bind -lazy_bind myApp.App/myApp</p>
</blockquote>
<p>优化该阶段的关键在于减少__DATA segment中的指针数量。我们可以优化的点有：</p>
<ul>
<li><p>减少Objc类数量， 减少selector数量</p>
</li>
<li><p>减少C++虚函数数量</p>
</li>
<li><p>转而使用swift stuct（其实本质上就是为了减少符号的数量）</p>
</li>
</ul>
<h3 id="Objc-setup"><a href="#Objc-setup" class="headerlink" title="Objc setup"></a>Objc setup</h3><p>这一步主要工作是:</p>
<ul>
<li>注册Objc类 (class registration)</li>
<li>把category的定义插入方法列表 (category registration)</li>
<li>保证每一个selector唯一 (selctor uniquing)</li>
</ul>
<p>由于之前2步骤的优化，这一步实际上没有什么可做的。</p>
<h3 id="initializers"><a href="#initializers" class="headerlink" title="initializers"></a>initializers</h3><p>以上三步属于静态调整(fix-up)，都是在修改__DATA segment中的内容，而这里则开始动态调整，开始在堆和堆栈中写入内容。 在这里的工作有：</p>
<ul>
<li>Objc的+load()函数</li>
<li>C++的构造函数属性函数 形如attribute((constructor)) void DoSomeInitializationWork()</li>
<li>非基本类型的C++静态全局变量的创建(通常是类或结构体)(non-trivial initializer) 比如一个全局静态结构体的构建，如果在构造函数中有繁重的工作，那么会拖慢启动速度</li>
</ul>
<p>Objc的load函数和C++的静态构造函数采用由底向上的方式执行，来保证每个执行的方法，都可以找到所依赖的动态库。</p>
<img src="/blogwebpage/images/iOS/applaunch_dyld.jpeg" class="" title="applaunch_dyld">

<p>上图是在自定义的类XXViewController的+load方法断点的调用堆栈，清楚的看到整个调用栈和顺序：</p>
<ul>
<li>dyld 开始将程序二进制文件初始化</li>
<li>交由 ImageLoader 读取 image，其中包含了我们的类、方法等各种符号</li>
<li>由于 runtime 向 dyld 绑定了回调，当 image 加载到内存后，dyld 会通知 runtime 进行处理</li>
<li>runtime 接手后调用 mapimages 做解析和处理，接下来 loadimages 中调用 callloadmethods 方法，遍历所有加载进来的 Class，按继承层级依次调用 Class 的 +load 方法和其 Category 的 +load 方法</li>
</ul>
<p>至此，可执行文件中和动态库所有的符号(Class，Protocol，Selector，IMP，…)都已经按格式成功加载到内存中，被 runtime 所管理，再这之后，runtime 的那些方法(动态添加 Class、swizzle 等等才能生效)。<br>整个事件由 dyld 主导，完成运行环境的初始化后，配合 ImageLoader 将二进制文件按格式加载到内存， 动态链接依赖库，并由 runtime 负责加载成 objc 定义的结构，所有初始化工作结束后，dyld 调用真正的 main 函数。<br>如果程序刚刚被运行过，那么程序的代码会被dyld缓存，因此即使杀掉进程再次重启加载时间也会相对快一点，如果长时间没有启动或者当前dyld的缓存已经被其他应用占据，那么这次启动所花费的时间就要长一点</p>
<h2 id="main-之前的加载时间如何衡量"><a href="#main-之前的加载时间如何衡量" class="headerlink" title="main()之前的加载时间如何衡量"></a>main()之前的加载时间如何衡量</h2><p>那么问题就来了，那怎么衡量main()之前也就是time1的耗时呢，苹果官方提供了一种方法，那就是在真机调试的时候勾选DYLD_PRINT_STATISTICS选项。</p>
<p>会得到如下形式的输出：</p>
<figure class="highlight apache"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">Total</span> pre-main time:  <span class="number">42</span>.<span class="number">89</span> milliseconds (<span class="number">100</span>.<span class="number">0</span>%)</span><br><span class="line">         <span class="attribute">dylib</span> loading time:  <span class="number">38</span>.<span class="number">75</span> milliseconds (<span class="number">90</span>.<span class="number">3</span>%)</span><br><span class="line">        <span class="attribute">rebase</span>/binding time: <span class="number">411015771</span>.<span class="number">6</span> seconds (<span class="number">80806899</span>.<span class="number">0</span>%)</span><br><span class="line">            <span class="attribute">ObjC</span> setup time:   <span class="number">3</span>.<span class="number">69</span> milliseconds (<span class="number">8</span>.<span class="number">6</span>%)</span><br><span class="line">           <span class="attribute">initializer</span> time:  <span class="number">17</span>.<span class="number">68</span> milliseconds (<span class="number">41</span>.<span class="number">2</span>%)</span><br><span class="line">           <span class="attribute">slowest</span> intializers :</span><br><span class="line">             <span class="attribute">libSystem</span>.B.dylib :   <span class="number">3</span>.<span class="number">07</span> milliseconds (<span class="number">7</span>.<span class="number">1</span>%)</span><br><span class="line">   <span class="attribute">libBacktraceRecording</span>.dylib :   <span class="number">2</span>.<span class="number">43</span> milliseconds (<span class="number">5</span>.<span class="number">6</span>%)</span><br><span class="line">    <span class="attribute">libMainThreadChecker</span>.dylib :   <span class="number">9</span>.<span class="number">07</span> milliseconds (<span class="number">21</span>.<span class="number">1</span>%)</span><br><span class="line">                    <span class="attribute">AppProject</span> :   <span class="number">1</span>.<span class="number">56</span> milliseconds (<span class="number">3</span>.<span class="number">6</span>%)</span><br></pre></td></tr></table></figure>

<p>由此可见，最多的用时还是在image加载和OC类的初始化，共占用总时长的79.3%，精简framework的引入和OC类有优化的空间。<br>总结一下：对于main()调用之前的耗时我们可以优化的点有：</p>
<ul>
<li><p>减少不必要的framework，因为动态链接比较耗时</p>
</li>
<li><p>check framework应当设为optional和required，如果该framework在当前App支持的所有iOS系统版本都存在，那么就设为required，否则就设为optional，因为optional会有些额外的检查</p>
</li>
<li><p>合并或者删减一些OC类，关于清理项目中没用到的类，使用工具AppCode代码检查功能，查到当前项目中没有用到的类如下：</p>
</li>
<li><p>删减一些无用的静态变量</p>
</li>
<li><p>删减没有被调用到或者已经废弃的方法</p>
  <figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">    方法见：http:<span class="regexp">//</span>stackoverflow.com<span class="regexp">/questions/</span><span class="number">35233564</span>/how-to-find-unused-code-<span class="keyword">in</span>-xcode-<span class="number">7</span></span><br><span class="line">https:<span class="regexp">//</span>developer.Apple.com<span class="regexp">/library/i</span>os<span class="regexp">/documentation/</span>ToolsLanguages<span class="regexp">/Conceptual/</span>Xcode_Overview/CheckingCodeCoverage.html</span><br></pre></td></tr></table></figure></li>
<li><p>将不必须在+load方法中做的事情延迟到+initialize中</p>
</li>
<li><p>尽量不要用C++虚函数(创建虚函数表有开销)</p>
</li>
</ul>
<h1 id="main-调用之后的加载时间"><a href="#main-调用之后的加载时间" class="headerlink" title="main()调用之后的加载时间"></a>main()调用之后的加载时间</h1><p>在main()被调用之后，App的主要工作就是初始化必要的服务，显示首页内容等。而我们的优化也是围绕如何能够快速展现首页来开展。 App通常在AppDelegate类中的- (BOOL)Application:(UIApplication *)Application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中创建首页需要展示的view，然后在当前runloop的末尾，主动调用CA::Transaction::commit完成视图的渲染。<br>而视图的渲染主要涉及三个阶段：</p>
<ul>
<li>准备阶段 这里主要是图片的解码</li>
<li>布局阶段 首页所有UIView的- (void)layoutSubViews()运行</li>
<li>绘制阶段 首页所有UIView的- (void)drawRect:(CGRect)rect运行<br>再加上启动之后必要服务的启动、必要数据的创建和读取，这些就是我们可以尝试优化的地方</li>
</ul>
<p>因此，对于main()函数调用之前我们可以优化的点有：</p>
<ul>
<li>不使用xib，直接视用代码加载首页视图</li>
<li>NSUserDefaults实际上是在Library文件夹下会生产一个plist文件，如果文件太大的话一次能读取到内存中可能很耗时，这个影响需要评估，如果耗时很大的话需要拆分(需考虑老版本覆盖安装兼容问题)</li>
<li>每次用NSLog方式打印会隐式的创建一个Calendar，因此需要删减启动时各业务方打的log，或者仅仅针对内测版输出log</li>
<li>梳理应用启动时发送的所有网络请求，是否可以统一在异步线程请求</li>
</ul>
<h1 id="如何找到拖慢启动应用时长的瓶颈"><a href="#如何找到拖慢启动应用时长的瓶颈" class="headerlink" title="如何找到拖慢启动应用时长的瓶颈"></a>如何找到拖慢启动应用时长的瓶颈</h1><p>为了找到瓶颈，我们在启动之后的didFinishLauhcning方法开始执行到首页列表页的NewsListViewController的viewDidAppear方法，几乎每个可能比较耗时的流程进行拆分和统计，得到统计数据之后发现： 主要耗时在首页UI构造和渲染(storyboard加载，tabBar/topBar渲染，开屏广告加载/cell注册/日志模块初始化这几个步骤)。</p>
<h1 id="具体优化点"><a href="#具体优化点" class="headerlink" title="具体优化点"></a>具体优化点</h1><p>因此，可以优化的点如下：</p>
<ul>
<li>纯代码方式而不是storyboard加载首页UI。</li>
<li>对didFinishLaunching里的函数考虑能否挖掘可以延迟加载或者懒加载，需要与各个业务方pm和rd共同check 对于一些已经下线的业务，删减冗余代码。<br>对于一些与UI展示无关的业务，如微博认证过期检查、图片最大缓存空间设置等做延迟加载</li>
<li>对实现了+load()方法的类进行分析，尽量将load里的代码延后调用。</li>
<li>上面统计数据显示展示feed的导航控制器页面(NewsListViewController)比较耗时，对于viewDidLoad以及viewWillAppear方法中尽量去尝试少做，晚做，不做。</li>
</ul>

    </div>

    
    
    
        <div class="reward-container">
  <div>希望对您有所帮助，您的支持将是我莫大的动力！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blogwebpage/images/wechatpay.png" alt="Jack Wang 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blogwebpage/images/alipay.png" alt="Jack Wang 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blogwebpage/tags/app%E5%90%AF%E5%8A%A8%E4%BC%98%E5%8C%96/" rel="tag"># app启动优化</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blogwebpage/iOS/interview/crash.html" rel="prev" title="Crash Report">
      <i class="fa fa-chevron-left"></i> Crash Report
    </a></div>
      <div class="post-nav-item">
    <a href="/blogwebpage/iOS/thirdpart/sdwebimage.html" rel="next" title="SDWebImage">
      SDWebImage <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#main-%E8%B0%83%E7%94%A8%E4%B9%8B%E5%89%8D%E7%9A%84%E5%8A%A0%E8%BD%BD%E8%BF%87%E7%A8%8B"><span class="nav-number">1.</span> <span class="nav-text">main()调用之前的加载过程</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%B3%BB%E7%BB%9F%E4%BD%BF%E7%94%A8%E5%8A%A8%E6%80%81%E9%93%BE%E6%8E%A5%E6%9C%89%E5%87%A0%E7%82%B9%E5%A5%BD%E5%A4%84%EF%BC%9A"><span class="nav-number">1.1.</span> <span class="nav-text">系统使用动态链接有几点好处：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFImageLoader"><span class="nav-number">1.2.</span> <span class="nav-text">什么是ImageLoader</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8A%A8%E6%80%81%E9%93%BE%E6%8E%A5%E5%BA%93%E5%8A%A0%E8%BD%BD%E7%9A%84%E5%85%B7%E4%BD%93%E6%B5%81%E7%A8%8B"><span class="nav-number">1.3.</span> <span class="nav-text">动态链接库加载的具体流程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#load-dylibs-image"><span class="nav-number">1.3.1.</span> <span class="nav-text">load dylibs image</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#rebase-bind"><span class="nav-number">1.3.2.</span> <span class="nav-text">rebase&#x2F;bind</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Objc-setup"><span class="nav-number">1.3.3.</span> <span class="nav-text">Objc setup</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#initializers"><span class="nav-number">1.3.4.</span> <span class="nav-text">initializers</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#main-%E4%B9%8B%E5%89%8D%E7%9A%84%E5%8A%A0%E8%BD%BD%E6%97%B6%E9%97%B4%E5%A6%82%E4%BD%95%E8%A1%A1%E9%87%8F"><span class="nav-number">1.4.</span> <span class="nav-text">main()之前的加载时间如何衡量</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#main-%E8%B0%83%E7%94%A8%E4%B9%8B%E5%90%8E%E7%9A%84%E5%8A%A0%E8%BD%BD%E6%97%B6%E9%97%B4"><span class="nav-number">2.</span> <span class="nav-text">main()调用之后的加载时间</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E6%89%BE%E5%88%B0%E6%8B%96%E6%85%A2%E5%90%AF%E5%8A%A8%E5%BA%94%E7%94%A8%E6%97%B6%E9%95%BF%E7%9A%84%E7%93%B6%E9%A2%88"><span class="nav-number">3.</span> <span class="nav-text">如何找到拖慢启动应用时长的瓶颈</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%85%B7%E4%BD%93%E4%BC%98%E5%8C%96%E7%82%B9"><span class="nav-number">4.</span> <span class="nav-text">具体优化点</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Jack Wang"
      src="/blogwebpage/images/avatar.gif">
  <p class="site-author-name" itemprop="name">Jack Wang</p>
  <div class="site-description" itemprop="description">书山有路勤为径，学海无涯苦作舟！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blogwebpage/archives/">
        
          <span class="site-state-item-count">52</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blogwebpage/categories/">
          
        <span class="site-state-item-count">56</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blogwebpage/tags/">
          
        <span class="site-state-item-count">54</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Jack-Ving"><i class="github fa-fw"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOjcyNzg4MTk0NUBxcS5jb20=" title="E-Mail → mailto:727881945@qq.com"><i class="envelope fa-fw"></i>E-Mail</span>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><span class="exturl" data-url="aHR0cHM6Ly9iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备16036665号-2 </span>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jack Wang</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> 强力驱动
  </div>

        


  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1277804316&web_id=1277804316"></script>
  </div>






      </div>
    </footer>
  </div>

  
  <script src="/blogwebpage/lib/anime.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.ui.min.js"></script>

<script src="/blogwebpage/js/utils.js"></script>

<script src="/blogwebpage/js/motion.js"></script>


<script src="/blogwebpage/js/schemes/pisces.js"></script>


<script src="/blogwebpage/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/blogwebpage/js/local-search.js"></script>













  

  

</body>
</html>
